package com.offcn.scwuser.controller;

import com.offcn.dycommon.response.AppResponse;
import com.offcn.scwuser.component.SmsTemplate;
import com.offcn.scwuser.pojo.TMember;
import com.offcn.scwuser.service.UserService;
import com.offcn.scwuser.vo.req.UserRegistVo;
import com.offcn.scwuser.vo.req.UserRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录/注册模块（包括忘记密码等）")
@Slf4j
public class UserLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @ApiOperation("获取注册的验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true)
    })//@ApiImplicitParams：描述所有参数；@ApiImplicitParam描述某个参数
    @PostMapping("/sendCode")
public AppResponse<Object> sendCode(String phone){
    //生成验证码
    String code=UUID.randomUUID().toString().replace("-","").substring(0,6);
   //保存redis
    redisTemplate.opsForValue().set(phone,code,60*60*24*7, TimeUnit.SECONDS);

    //发送验证码
    Map<String,String> query=new HashMap<>();
    query.put("mobile",phone);
    query.put("param","code:"+code);
    query.put("tpl_id","TP1711063");
    //响应结构
    String sendCode=smsTemplate.sendCode(query);
    if(sendCode.equals("")||sendCode.equals("fail")){
        return AppResponse.fail("发送失败");
    }else{
        return AppResponse.ok("成功");
    }

    }
    //注册
    @ApiOperation("用户注册")
    @PostMapping
    public AppResponse<Object> register(UserRegistVo registVo){
        TMember tMember = new TMember();
        //1核验验证码是否正确
        String s = redisTemplate.opsForValue().get(registVo.getLoginacct());
        if (s!=null&&s.equals(registVo.getCode())){
            //2register--->tmeber里面惊醒数据填充
            BeanUtils.copyProperties(registVo,tMember);//里面第一个放源头，第二个放目的的
            //3、将用户信息注册到数据库
            try {
                userService.registerUser(tMember);
                log.debug("用户信息注册成功：{}", tMember.getLoginacct());
                //4、注册成功后，删除验证码
                redisTemplate.delete(registVo.getLoginacct());
                return AppResponse.ok("注册成功...");
            } catch (Exception e) {
                log.error("用户信息注册失败：{}", tMember.getLoginacct());
                return AppResponse.fail(e.getMessage());
               }
             } else {
            return AppResponse.fail("验证码错误");
           }
    }
    //登陆
    @ApiOperation("用户登陆")
    @RequestMapping("/login")
    public AppResponse<UserRespVo> login(String username,String password){
        TMember member = userService.login(username, password);
        if (member==null){
            AppResponse<UserRespVo> fail=AppResponse.fail(null);
           fail.setMes("用户名不对");
            return fail;
        }
        //成功
        //生成令牌，---存redis
        String userToken = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(userToken,member.getId()+"");
        UserRespVo userRespVo=new UserRespVo();
        BeanUtils.copyProperties(member,userRespVo);
        userRespVo.setAccessToken(userToken);
        return AppResponse.ok(userRespVo);
    }

}
